package ru.agiledev.akb.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.hibernate.Query;
import org.hibernate.Session;
import ru.agiledev.akb.client.AKBDataService;
import ru.agiledev.akb.server.hibernate.HibernateUtil;
import ru.agiledev.akb.server.logic.DataManager;
import ru.agiledev.akb.shared.QType;
import ru.agiledev.akb.shared.TransferObject;

import java.util.List;


/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class AKBDataServiceImpl extends RemoteServiceServlet implements AKBDataService {

   @Override
    public TransferObject getData(Integer id) {
        String question = "Каковы характеристики X?";
        String[] iObjects = {"характеристики", "X"};
        String[] aspects = {"мощность","объем","вес"};
       String[] examples = {"",""};


        return new TransferObject(1, question, QType.CHARS_DESCRIPTION, iObjects, aspects, examples, null);
    }

    @Override
    public void saveData(TransferObject dto) throws Exception {
        if((dto!=null)&&checkDTO(dto)){
            DataManager.saveEntry(dto);
        }

        //TODO: saving data
    }

    @Override
    public Integer[] getIds() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Query query = session.createQuery("select id from Question");

        List<Integer> ids =  query.list();

        return (Integer[])ids.toArray(new Integer[ids.size()]);
    }

    protected boolean checkDTO(TransferObject dto) throws Exception{

        return true;
    }

    @Override
    public TransferObject getDataForQuestion(String question) {
        return DataManager.getDataForQuestion(question);
    }

    @Override
    public TransferObject getDataForQuestion(Integer id) {
        return DataManager.getDataForQuestion(id);
    }

    @Override
    public void updateData(TransferObject tObject) throws Exception {
        DataManager.updateEntry(tObject);
    }
}
